package com.we823.project.controller.repo;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.we823.project.controller.AbstractSimpleBaseController;
import com.we823.project.core.web.WebConstants;
import com.we823.project.model.repo.CategoryModel;
import com.we823.project.repository.service.repo.CategoryService;
import com.we823.utils.web.RequestUtil;

@Controller
@RequestMapping(WebConstants.REPO_CATEGORY)
public class CategoryController extends AbstractSimpleBaseController<CategoryModel,Integer> {

	private String baseUrl = WebConstants.REPO_CATEGORY_TEMPLATE;

	private CategoryService categoryService;

	@Autowired
	public CategoryController(CategoryService categoryService) {
		super(categoryService);
		this.categoryService = categoryService;
		super.baseUrl = baseUrl;
		setResourceIdentity("data:category");
	}

	@Override
	public Page<CategoryModel> getData(PageRequest pageRequest, HttpServletRequest request, Model model, boolean pageable) {
		Page<CategoryModel> categoryPage = null;
		if (pageable) {
			if (pageRequest != null) {
				categoryPage = categoryService.findAll(pageRequest);
			}
		} else {
			categoryPage = new PageImpl<>(categoryService.findAll());
		}
		return categoryPage;
	}

	@Override
	public CategoryModel getEntity(HttpServletRequest request, Integer id,String oper) {
		String name = RequestUtil.getValueByParam(request, "name");
		String code = RequestUtil.getValueByParam(request, "code");
		Date addtime = RequestUtil.getValueByParam(request, "addtime",new Date());
		CategoryModel categoryModel = new CategoryModel();
		categoryModel.setName(name);
		categoryModel.setCode(code);
		categoryModel.setAddtime(addtime);
		categoryModel.setEdittime(new Date());
		
		if(id!=null && id>0){
			categoryModel.setId(id);
		}
		return categoryModel;
	}

	
	@Override
	protected Sort getSort(HttpServletRequest request) {
		return new Sort(Direction.ASC,"code");
	}
}
